package jp.co.dailyReport;

import java.sql.Connection;
import java.sql.SQLException;
import org.apache.log4j.Logger;

public class ExecuterManager {
	private static Logger log = Logger.getLogger(ExecuterManager.class);

	public static Object[] execute(ConnectionFactory connectionFactory, Executer executer)
		 throws SQLException {

		Executer executers[] = { executer };
		Object answer[][] = execute(connectionFactory, executers);
		return answer[0];
	}

    public static Object[][] execute(ConnectionFactory connectionFactory, Executer executers[])
		 throws SQLException {
		Object answer[][] = new Object[executers.length][];
		Connection conn = null;
		try {
			conn = connectionFactory.createConnection();
			conn.setAutoCommit(false);
			for(int i = 0; i < executers.length; i++){
				answer[i] = executers[i].execute(conn);
			}
			conn.commit();
			log.debug("do commit ");
		} catch(SQLException sqle) {
			log.error("do rollback... " + sqle.toString(), sqle);
			conn.rollback();
			throw new SQLException("do rollback... " + sqle.toString());
		} finally {
			try {
				if(conn != null) {
					conn.close();
					conn = null;
				}
			} catch(SQLException sqle) {
				log.error(sqle.toString(), sqle);
				throw new SQLException(sqle.toString());
			} finally {
				try {
					if(conn != null)
						 conn.close();
				} catch(SQLException sqle2) {
					log.fatal(sqle2.toString(), sqle2);
					throw new SQLException(sqle2.toString());
				}
			}
		}
		return answer;
	}

}
